package com.thank.concurrency.samples.syncContainer;

import com.thank.concurrency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Vector;

/**
 * 演示Vector 同步容器线程不安全的情况
 */
@NotThreadSafe
@Slf4j
public class VectorExample2 {

    private static List<Integer> vector = new Vector<>();

    public static void main(String[] args) {
//        while (true) {
            for (int i = 0; i < 10; i++) {
                vector.add(i);
            }

            Thread thread1 = new Thread(() -> {
                for (int i = 0; i < vector.size(); i++) {
                    log.info("remove: {}", i);
                    vector.remove(i);
                }
            });

            Thread thread2 = new Thread(() -> {

                for (int i = 0; i < vector.size(); i++) {
                    // 例如thread2想获取i=9的元素的时候，thread1将i=9的元素移除了，导致数组越界
                    log.info("get: {}", i);
                    vector.get(i);
                }
            });

            thread1.start();
            thread2.start();
        }
//    }
}
